package com.pet.file.controller;

import com.pet.common.domain.Result;
import com.pet.file.utils.FileUploadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Api(tags = "文件上传")
@RestController
@RequestMapping("/files")
public class FileController {
    @Value("${file.storage.path}")
    private String uploadPath;

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result upload(@RequestParam("file") MultipartFile uploadFile) {
        String oldName = uploadFile.getOriginalFilename();
        String fileName = UUID.randomUUID().toString();
        String newName = fileName + oldName.substring(oldName.lastIndexOf("."));
        boolean isSucceed = FileUploadUtil.uploadToServer(uploadFile, uploadPath, newName);
        return isSucceed ? Result.success(newName) : Result.error();
    }
}
